import { mutations } from '@/store/mutations'

const state = {
  tabs: [],
  index: 0
}

const actions = {
  // remove token

  addTabItem({ commit, state }, addItem) {
    let isAdd = true
    let tempIndex = state.index
    state.tabs.forEach((item, index) => {
      if (item.component === addItem.component) {
        isAdd = false
        tempIndex = index
      }
    })
    if (isAdd) {
      state.tabs.push(addItem)
      commit('SET_ATTR', { key: 'tabs', data: state.tabs })
      commit('SET_ATTR', { key: 'index', data: state.tabs.length - 1 })
    } else {
      commit('SET_ATTR', { key: 'index', data: tempIndex })
    }
  },

  changeTabIndex({ commit }, index) {
    commit('SET_ATTR', { key: 'index', data: index })
  },
  deleteTabIndex({ commit, state }, index) {
    delete state.tabs[index]
    const tempTabs = []
    state.tabs.forEach((item) => {
      if (item) {
        tempTabs.push(item)
      }
    })
    if (index > tempTabs.length - 1) {
      index = tempTabs.length - 1
    }
    if (index < 0) {
      index = 0
    }
    commit('SET_ATTR', { key: 'tabs', data: tempTabs })
    commit('SET_ATTR', { key: 'index', data: index })
  },

  closeOther({ commit, state }, index) {
    const newTabs = state.tabs.splice(index, 1)
    commit('SET_ATTR', { key: 'tabs', data: newTabs })
    commit('SET_ATTR', { key: 'index', data: 0 })
  },
  deleteTabTabs({ commit }) {
    commit('SET_ATTR', { key: 'tabs', data: [] })
    commit('SET_ATTR', { key: 'index', data: 0 })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
